﻿using Microsoft.Extensions.Logging;

using PLCS.Application.Contracts.TaskApp.Dtos;

using Prism.Commands;

namespace PLCS.App.OrderTask.ViewModels.Instruction
{
    public class InstructionViewModel : NavigationPagedCurdViewModel<InstructionDto, InstructionEditDto, IInstructionService>
    {
        private readonly ILogger<InstructionViewModel> _logger;
        private string _instructionNo, _equipmentNo, _status;

        public DelegateCommand<InstructionDto> SubmitCommand { get; }

        public DelegateCommand<InstructionDto> AgainIssuedCommand { get; }

        public string InstructionNo
        {
            get { return _instructionNo; }
            set { SetProperty(ref _instructionNo, value); }
        }

        public string EquipmentNo
        {
            get { return _equipmentNo; }
            set { SetProperty(ref _equipmentNo, value); }
        }

        public string Status
        {
            get { return _status; }
            set { SetProperty(ref _status, value); }
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="pageIndex"></param>
        public override async Task GetPageData(int pageIndex)
        {
            try
            {
                UpdateLoading(true);
                var res = await _service.GetListBySearchAsync((pageIndex - 1) * PageSize, PageSize, InstructionNo, EquipmentNo, Status);
                TotalCount = (int)res.TotalCount;
                SetPageCount();
                DataGridList = res.Items.ToObservable();
            }
            finally
            {
                UpdateLoading(false);
            }
        }

        public InstructionViewModel(IInstructionService service, ILogger<InstructionViewModel> logger) : base(service)
        {
            SubmitCommand = new DelegateCommand<InstructionDto>(Submit);
            AgainIssuedCommand = new DelegateCommand<InstructionDto>(AgainIssued);
            _logger = logger;
            View = "指令管理";
        }

        private async void Submit(InstructionDto model)
        {
            try
            {
                await _service.FinshTaskAsync(model.Id);
                DataGridList.Remove(model);
                Log("手动报工", model);
                ShowMessage("手动报工成功");
            }
            catch (Exception ex)
            {
                ShowMessage("手动报工失败");
                _logger.LogException(ex);
            }
        }

        private async void AgainIssued(InstructionDto model)
        {
            try
            {
                await _service.AgainIssuedAsync(model.Id);
                Log("重新下发", model);
                await RefreshAsync();
                ShowMessage("重新下发成功");
            }
            catch (Exception ex)
            {
                ShowMessage("重新下发失败");
                _logger.LogException(ex);
            }
        }
    }
}